package com.company.common.function.filter.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

////指定要拦截的路径
//@WebFilter(urlPatterns = "/api/*",filterName = "myFilter")
////执行指定顺序
//@Order(1)

//注意实现 javax.servlet 过滤器
public class MyFilter implements Filter {

    //添加白名单（开放性api）
    @Value("${open.url}")
    private String openUrl;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("MyFilter 被初始化了");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        String method = request.getMethod();
        System.out.println("请求的接口=" + uri + "请求的方式" + method);
        //判断是否是开放性api 是通过 不是对凭证进行校验
        AntPathMatcher pathMatcher = new AntPathMatcher();
        //进入路径
        if (pathMatcher.match(openUrl, uri)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            String token = request.getHeader("token");
            //判断是否携带凭证
            //判断
            if (StringUtils.isEmpty(token)) {
                //没传token 获取新路径进入
                servletRequest.getRequestDispatcher("/api/open/unLogin").forward(servletRequest, servletResponse);
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("MyFilter 被销毁了");
    }
}
